package me.hl.guava.loadingCache;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * Created by planck on 2016/7/29.
 */
public class CacheTest {

    private static Logger logger = LoggerFactory.getLogger(CacheTest.class);

    private final static Cache<String, Object> cache = CacheBuilder.newBuilder().maximumSize(10000)
            .expireAfterAccess(5, TimeUnit.SECONDS)
            .build();


    @Test
    public void testCacheTest() {
        try {
            //会自动等去把return等值load进cache里面。
            cache.get("111", () -> {
                return "1111";
            });
            logger.info(cache.get("111", () -> "2222").toString());
            Thread.sleep(5000);
            logger.info(cache.get("111", () -> "3333").toString());
            logger.info(cache.get("111", () -> "4444").toString());
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    @Test
    public void testCacheLoad() throws Exception {
        for (int i = 0; i < 10; i++) {
            Thread thread1 = new Thread(() -> {
                try {
                    Object o = cache.get("1111", () -> {
                        logger.info("insert");
                        Thread.sleep(1111);
                        return "1111";
                    });
                    logger.info(o.toString());
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            });
            thread1.run();
        }

        Thread.sleep(100000);


    }
}
